var gulp = require('gulp');
var connect = require('gulp-connect');
var htmlmin = require('gulp-htmlmin');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var cssnano = require('gulp-cssnano');
var uglify = require('gulp-uglify');

gulp.task('watch', function () {
  gulp.watch('src/*.html', ['html']);
  gulp.watch('src/js/*.js', ['js']);
  gulp.watch('src/css/*.css', ['css']);
  gulp.watch('src/images/*.*', ['img']);
});

gulp.task('img', function () {
  gulp.src('src/images/*.*')
    .pipe(gulp.dest('dist/images'))
    .pipe(connect.reload())
});

gulp.task('css', function () {
  gulp.src('src/css/*.css')
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(postcss([autoprefixer()]))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist/css'))
    .pipe(connect.reload())
});

gulp.task('js', function () {
  gulp.src('src/js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
    .pipe(connect.reload())
});

gulp.task('html', function () {
  gulp.src('src/*.html')
    .pipe(htmlmin({
      collapseWhitespace: true
    }))
    .pipe(gulp.dest('dist/'))
    .pipe(connect.reload());
});

gulp.task('connect', function () {
  connect.server({
    port: '3333',
    livereload: true
  });
});

gulp.task('default', ['connect', 'watch', 'html', 'js', 'css', 'img']);